<template>
	<div>
		<el-card>
			<el-form :model="state.pageParam.param" label-width="120"  ref="queryFormRef" @keyup.enter.native="loadList">
				<el-row :gutter="10">
					<el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6">
						<el-form-item v-if="state.istenant && userInfos.tenantId === '1'" prop="tenantName" label="租户名称">
							<el-input v-model="state.pageParam.param.tenantName" class="task-head-search-input"  placeholder="租户名称" clearable>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6">
						<el-form-item label="角色名称" prop="roleName">
							<el-input v-model="state.pageParam.param.roleName" placeholder="角色名称" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div class="btnSearchStyle">
				<el-button type="primary" class="ml7" @click="loadList">
					<el-icon>
						<ele-Search />
					</el-icon>
					查询
				</el-button>
				<el-button type="primary" class="ml10" @click="reSetForm(queryFormRef)">
					<el-icon>
						<ele-Refresh />
					</el-icon>
					重置
				</el-button>
			</div>
		</el-card>
		<el-card>
			<div class="btnStyle">
				<el-button  type="success" icon="ele-Plus" @click="addOrUpdateHandle()">新增</el-button>
			</div>
			<el-table :data="state.dataList" stripe style="width: 100%" v-loading="state.listLoading">
				<el-table-column v-if="state.istenant && userInfos.tenantId === '1'"
					prop="tenantName" header-align="center" align="center" label="租户"/>
				<el-table-column prop="roleName" header-align="center" align="center" label="角色名称"/>
				<el-table-column prop="remark" header-align="center" align="center" label="备注"/>
				<el-table-column fixed="right" header-align="center" align="center" width="250" label="操作">
					<template #default="scope">
						<el-button type="primary" link  @click="updateHandle(scope.row)" >修改</el-button>
						<el-button type="primary" link  @click="setResEditLineHandle(scope.row)"  >设置资源权限</el-button>
						<el-button type="primary" link  @click="deleteHandle(scope.row.id)"  >删除</el-button>
						<el-button type="primary" link  @click="roleUserMngHandle(scope.row.id)" >用户维护</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="onHandleSizeChange"
				@current-change="onHandleCurrentChange"
				:pager-count="5"
				:page-sizes="[10, 50, 200]"
				v-model:current-page="state.pageParam.page"
				background
				v-model:page-size="state.pageParam.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.total" small>
			</el-pagination>
		</el-card>
		<el-dialog :close-on-click-modal="false" :title="!state.submitForm.id ? '新增' : '修改'" ref="addOrUpdate" v-model="state.addOrUpdateVisible">
			<el-form :model="state.submitForm" :rules="state.submitFormRule" ref="ruleFormRef" @keyup.enter.native="dataFormSubmit(ruleFormRef)" label-width="120px">
				<el-form-item v-if="state.istenant && userInfos.tenantId === '1'" label="租户" prop="tenantId" >
					<DicSelect v-model="state.submitForm.tenantId" placeholder="请选择" isTenantSelect="true" style="width:100%" @change="reLoadResTree"></DicSelect>
					<!-- <el-select v-model="state.submitForm.tenantId" placeholder="" :filterable="true" :disabled="!(!state.submitForm.id)" style="width: 100%;" @change="reLoadResTree">
						<el-option v-for="(item,index) in state.tenantSelect" :key="item.key" :label="item.value" :value="item.key"></el-option>
					</el-select> -->
				</el-form-item>
				<el-form-item label="角色名称" prop="roleName">
					<el-input v-model="state.submitForm.roleName" placeholder="角色名称" maxlength="100"></el-input>
				</el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input v-model="state.submitForm.remark" placeholder="备注" maxlength="100"></el-input>
				</el-form-item>
				<el-form-item  label="授权">
					<el-tree :data="state.menuList" ref="treeRoleMenuRef" node-key="id" :props="state.menuListTreeProps"  show-checkbox  :check-strictly="false"  :highlight-current="true" v-loading="state.treeLoading" style="width: 100%;">
					</el-tree>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.addOrUpdateVisible = false">取消</el-button>
					<el-button type="primary" @click="dataFormSubmit(ruleFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog :close-on-click-modal="false" title="设置资源权限" v-model="state.roleMenuSetVisible">
			<el-tree :data="state.menuListOnly" ref="treeRoleMenuOnlyRef" node-key="id" :props="state.menuListTreeProps"  show-checkbox  :check-strictly="false"  :highlight-current="true" v-loading="state.treeLoading" style="width: 100%;">
			</el-tree>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.roleMenuSetVisible = false">取消</el-button>
					<el-button type="primary" @click="resOnlySubmit()">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog :close-on-click-modal="false" title="设置角色用户" v-model="state.roleUserMngVisible">
			<el-form :model="state.roleUserQueryForm" :inline="true" ref="roleUserQueryFormRef" @keyup.enter.native="loadRoleUserMngList">
				<el-row>
					<el-col :span="8">
						<el-form-item label="用户名">
							<el-input v-model="state.roleUserQueryForm.param.username" placeholder="用户名"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="姓名">
							<el-input v-model="state.roleUserQueryForm.param.staffName" placeholder="姓名"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-button type="primary" class="ml7" @click="loadRoleUserMngList">
							<el-icon>
								<ele-Search />
							</el-icon>
							查询
						</el-button>
						<el-button type="primary" class="ml10" @click="reSetRoleUserMngForm(roleUserQueryFormRef)">
							<el-icon>
								<ele-Refresh />
							</el-icon>
							重置
						</el-button>
					</el-col>
				</el-row>
				
			</el-form>
			<div class="btnStyle">
				<el-button  type="success" icon="ele-Plus" @click="addRoleUsers()">新增</el-button>
			</div>
			<el-table :data="state.roleUserDataList" stripe style="width: 100%">
				<el-table-column prop="username" header-align="center" align="center" label="用户名"/>
				<el-table-column prop="staffName" header-align="center" align="center" label="备注"/>
				<el-table-column fixed="right" header-align="center" align="center" width="250" label="操作">
					<template #default="scope">
						<el-button type="primary" v-if="scope.row.userId !== '1'" link  @click="deleteRoleUserHandle(scope.row.id)" >删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="onUserRoleHandleSizeChange"
				@current-change="onUserRoleHandleCurrentChange"
				:pager-count="5"
				:page-sizes="[10, 50, 200]"
				v-model:current-page="state.roleUserQueryForm.page"
				background
				v-model:page-size="state.roleUserQueryForm.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.total" small>
			</el-pagination>
		</el-dialog>
		<el-dialog :close-on-click-modal="false" title="选择用户" v-model="state.roleUserSelectVisible">
			<el-form :model="state.roleUserSelectForm" :inline="true" ref="roleUserSelectFormRef" @keyup.enter.native="loadRoleUserSelectList">
				<el-row>
					<el-col :span="8">
						<el-form-item label="用户名">
							<el-input v-model="state.roleUserSelectForm.param.username" placeholder="用户名"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="姓名">
							<el-input v-model="state.roleUserSelectForm.param.staffName" placeholder="姓名"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-button type="primary" class="ml7" @click="loadRoleUserSelectList">
							<el-icon>
								<ele-Search />
							</el-icon>
							查询
						</el-button>
						<el-button type="primary" class="ml10" @click="reSetRoleUserSelectForm(roleUserSelectFormRef)">
							<el-icon>
								<ele-Refresh />
							</el-icon>
							重置
						</el-button>
					</el-col>
				</el-row>
			</el-form>
			<el-table :data="state.roleUserSelectList" stripe style="width: 100%">
				<el-table-column prop="username" header-align="center" align="center" label="用户名"/>
				<el-table-column prop="staffName" header-align="center" align="center" label="备注"/>
				<el-table-column fixed="right" header-align="center" align="center" width="250" label="操作">
					<template #default="scope">
						<el-button type="primary"  link  @click="setRoleUserSelectHandle(scope.row.id)" >添加</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="onUserRoleSelectHandleSizeChange"
				@current-change="onUserRoleSelectHandleCurrentChange"
				:pager-count="5"
				:page-sizes="[10, 50, 200]"
				v-model:current-page="state.roleUserSelectForm.page"
				background
				v-model:page-size="state.roleUserSelectForm.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.total" small>
			</el-pagination>
		</el-dialog>
	</div>
</template>
<script setup lang="ts" name="role">
	import { ElMessage, ElTree, ElMessageBox, FormInstance, ElLoading } from 'element-plus'
	import { ref, reactive, onMounted, nextTick } from 'vue'
	import { systemApi } from '/@/api/sys/system-api'
	import { storeToRefs } from 'pinia';
	import { useUserInfo } from '/@/stores/userInfo'
	const { userInfos } = storeToRefs(useUserInfo())
	const queryFormRef = ref<FormInstance>()
	const ruleFormRef = ref<FormInstance>()
	const roleUserQueryFormRef = ref<FormInstance>()
	const	roleUserSelectFormRef = ref<FormInstance>()
	const treeRoleMenuRef = ref<InstanceType<typeof ElTree>>()
	const treeRoleMenuOnlyRef = ref<InstanceType<typeof ElTree>>()
	const state = reactive({
		istenant: import.meta.env.VITE_IS_TENANT as Boolean,
		listLoading: false,
		total: 0,
		dataList: [],
		dataListSelections: [],
		pageParam: {
			page: 1,
			pageSize: 10,
			param: {
				roleName: '',
				tenantName: '',
			}
		},
		addOrUpdateVisible: false,
		roleMenuSetVisible: false,
		menuList: [],
		menuListOnly: [],
		roleResours: [],
		treeLoading: false,
		menuListTreeProps: {
			children: 'children',
			label: 'name'
		},
		submitForm: {
			id: 0,
			roleName: '',
			remark: '',
			tenantId: import.meta.env.VITE_IS_TENANT ? '': userInfos.value.tenantId,
			resId: []
		},
		submitFormRule: {
			roleName: [
				{ required: true, message: '角色名称不能为空', trigger: 'blur' }
			],
			tenantId: [
				{ required: true, message: '租户不能为空', trigger: 'blur' }
			]
		},
		tempTenantId: '',
		tempRoleId: '',
		roleUserMngVisible: false,
		roleUserQueryForm: {
			page: 1,
			pageSize: 10,
			param: {
				roleId: '',
				username: '',
				staffName: '',
			}
		},
		roleUserDataList: [],
		roleUserSelectVisible: false,
		roleUserSelectForm: {
			page: 1,
			pageSize: 10,
			param: {
				roleId: '',
				username: '',
				staffName: '',
			}
		},
		roleUserSelectList: [],
	})
	const loadList = () => {
		state.listLoading = true
		systemApi.queryRoleListPage(state.pageParam).then(data => {
			if (data && data.code === 0) {
				state.dataList = data.data.records
				state.total = data.data.totalRow
			} else {
				state.dataList = []
				state.total = 0
			}
		}).catch(() => {
		}).finally(() => {
			state.listLoading = false
		})
	}
	// 页面加载时
	onMounted(() => {
		// 列表查询
		loadList()
	})

	//重置
	const reSetForm = (formEl: FormInstance | undefined) => {
		if (!formEl) return
		formEl.resetFields()
		state.pageParam.page = 1
		loadList()
	}
	// 分页改变
	const onHandleSizeChange = (val: number) => {
		state.pageParam.pageSize = val;
		loadList()
	}
	// 分页改变
	const onHandleCurrentChange = (val: number) => {
		state.pageParam.page = val;
		loadList()
	}
	const deleteHandle = (id: string | undefined) => {
			if(!id) {
				ElMessage.error('请选择记录！')
				return
			}
			ElMessageBox.confirm('是否确定删除所选记录', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
			}).then(() => {
				systemApi.deleteSysRoleInfo(id).then(data => {
					if (data && data.code === 0) {
						ElMessage.success('删除成功')
						loadList()
					} else {
						ElMessage.error(data.message)
					}
				}).catch(() => {
					ElMessage.error("删除失败")
				})
			})
		}
	//打开新增弹窗
	const addOrUpdateHandle = () => {
		state.submitForm = {
			id: 0,
			roleName: '',
			remark: '',
			tenantId: import.meta.env.VITE_IS_TENANT ? '': userInfos.value.tenantId,
			resId: []
		}
		state.addOrUpdateVisible = true
		state.menuList = []
	}
	//打开修改弹窗
	const updateHandle = (row: any | undefined) => {
		state.submitForm = {
			id: row.id,
			roleName: row.roleName,
			remark: row.remark,
			tenantId: row.tenantId,
			resId: []
		}
		state.addOrUpdateVisible = true
		reLoadResTree(row.tenantId)
	}
	const dataFormSubmit = (formEl: FormInstance | undefined) => {
		if (!formEl) return
		formEl.validate((valid: boolean) => {
			if (valid) {
				//提交数据
				let checkResIds = treeRoleMenuRef.value!.getCheckedKeys()
				checkResIds = checkResIds.concat(treeRoleMenuRef.value!.getHalfCheckedKeys())
				const loading = ElLoading.service({
					lock: true,
					text: '处理中',
					background: 'rgba(0, 0, 0, 0.7)',
				})
				state.submitForm.resId = checkResIds
				if(!state.submitForm.id) {
					//新增
					systemApi.saveSysRoleInfo(state.submitForm).then(data => {
						if (data && data.code === 0) {
							ElMessage.success('保存成功')
							state.addOrUpdateVisible = false
							loadList()
						} else {
							ElMessage.error(data.message)
						}
					}).catch(() => {
						ElMessage.error('保存失败')
					}).finally(() => {
						loading.close()
					})
				}else{
					systemApi.updateSysRoleInfo(state.submitForm).then(data => {
						if (data && data.code === 0) {
							ElMessage.success('保存成功')
							state.addOrUpdateVisible = false
							loadList()
						} else {
							ElMessage.error(data.message)
						}
					}).catch(() => {
						ElMessage.error('保存失败')
					}).finally(() => {
						loading.close()
					})
				}
			}
		})
	}
	const setResEditLineHandle = (row:any) => {
		state.menuListOnly = []
		state.roleMenuSetVisible = true
		state.tempTenantId = row.tenantId
		state.tempRoleId = row.id
		reLoadResTreeOnly(row.tenantId, row.id)
	}

	const reLoadResTree = (val:string) => {
		state.treeLoading = true
		if(!val)
		state.menuList = []
		systemApi.resetTenantRoleResTree(val, state.submitForm.id).then(data => {
			if (data) {
				state.menuList = data.data.tree
				state.roleResours = data.data.asingRes
				nextTick(() => {
					checkStation(data.data.asingRes)
				})
			} else {
				state.menuList = []
			}
		}).finally(() => {
			state.treeLoading = false
		})
	}
	const reLoadResTreeOnly = (tenantId:string, roleId:string) => {
		state.treeLoading = true
		if(!tenantId || !roleId)
		state.menuListOnly = []
		systemApi.resetTenantRoleResTree(tenantId, roleId).then(data => {
			if (data) {
				state.menuListOnly = data.data.tree
				state.roleResours = data.data.asingRes
				nextTick(() => {
					checkStationOnly(data.data.asingRes)
				})
			} else {
				state.menuListOnly = []
			}
		}).finally(() => {
			state.treeLoading = false
		})
	}
	const checkStation = (asingRes: any) => {
		var checkArray = new Array();
		if (asingRes) {
			asingRes.forEach((item: any, index: number, arr: any) => {
			if (treeRoleMenuRef.value!.getNode(item.menuId)) {
				if (treeRoleMenuRef.value!.getNode(item.menuId).isLeaf) {
				checkArray.push(item.menuId);
				}
			}
			});
			nextTick(() => {
				treeRoleMenuRef.value!.setCheckedKeys(checkArray, false);
			})
		}
	}
	const checkStationOnly = (asingRes: any) => {
		var checkArray = new Array();
		if (asingRes) {
			asingRes.forEach((item: any, index: number, arr: any) => {
			if (treeRoleMenuOnlyRef.value!.getNode(item.menuId)) {
				if (treeRoleMenuOnlyRef.value!.getNode(item.menuId).isLeaf) {
				checkArray.push(item.menuId);
				}
			}
			});
			nextTick(() => {
				treeRoleMenuOnlyRef.value!.setCheckedKeys(checkArray, false);
			})
		}
	}
	const resOnlySubmit = () => {
		let checkResIds = treeRoleMenuOnlyRef.value!.getCheckedKeys()
		checkResIds = checkResIds.concat(treeRoleMenuOnlyRef.value!.getHalfCheckedKeys())
		const loading = ElLoading.service({
			lock: true,
			text: '处理中',
			background: 'rgba(0, 0, 0, 0.7)',
		})
		systemApi.setSysRoleMenu(state.tempRoleId, checkResIds).then(data => {
			if (data && data.code === 0) {
				ElMessage.success('设置成功')
				state.roleMenuSetVisible = false
				loadList()
			} else {
				ElMessage.error(data.message)
			}
		}).catch(() => {
			ElMessage.error("保存失败")
		}).finally(() => {
			loading.close()
		})
	}
	const roleUserMngHandle = (id: string) => {
		state.roleUserMngVisible = true
		state.roleUserQueryForm.param.roleId = id
		roleUserQueryFormRef.value?.resetFields()
		loadRoleUserMngList()
	}
	const loadRoleUserMngList = () => {
		systemApi.getRoleUserDataListByRoleId(state.roleUserQueryForm).then(data => {
			if (data && data.code === 0) {
				state.roleUserDataList = data.data.records
				state.total = data.data.totalRow
			} else {
				state.roleUserDataList = []
				state.total = 0
			}
		}).catch(() => {
		}).finally(() => {
			state.listLoading = false
		})
	}
	const reSetRoleUserMngForm = (formEl: FormInstance | undefined) => {
		if (!formEl) return
		formEl.resetFields()
		state.roleUserQueryForm.page = 1
		loadRoleUserMngList()
	}
	const onUserRoleHandleSizeChange= (val: number) => {
		state.roleUserQueryForm.pageSize = val;
		loadRoleUserMngList()
	}
	const onUserRoleHandleCurrentChange = (val: number) => {
		state.roleUserQueryForm.page = val;
		loadRoleUserMngList()
	}
	const deleteRoleUserHandle = (id: string) => {
		systemApi.deleteRoleUserById(id).then(data => {
			if (data && data.code === 0) {
				state.roleUserDataList = data.data.records
				state.total = data.data.totalRow
			} else {
				state.roleUserDataList = []
				state.total = 0
			}
		}).catch(() => {
		}).finally(() => {
			// state.listLoading = false
		})
	}
	const addRoleUsers = () => {
		state.roleUserSelectVisible = true
		state.roleUserSelectForm.param.roleId = state.roleUserQueryForm.param.roleId
		loadRoleUserSelectList()
	}
	const loadRoleUserSelectList = () => {
		systemApi.getRoleUserSelectListByRoleId(state.roleUserQueryForm).then(data => {
			if (data && data.code === 0) {
				state.roleUserSelectList = data.data.records
				state.total = data.data.totalRow
			} else {
				state.roleUserSelectList = []
				state.total = 0
			}
		}).catch(() => {
		}).finally(() => {
			// state.listLoading = false
		})
	}
	const reSetRoleUserSelectForm = (formEl: FormInstance | undefined) => {
		if (!formEl) return
		formEl.resetFields()
		state.roleUserSelectForm.page = 1
		loadRoleUserSelectList()
	}
	const onUserRoleSelectHandleSizeChange = (val: number) => {
		state.roleUserQueryForm.pageSize = val;
		loadRoleUserSelectList()
	}
	const onUserRoleSelectHandleCurrentChange = (val: number) => {
		state.roleUserQueryForm.page = val;
		loadRoleUserSelectList()
	}
	const setRoleUserSelectHandle = (id: string) => {
		const data = {
			'userId': id,
			'roleId': state.roleUserQueryForm.param.roleId
		}
		systemApi.setRoleUserSelectHandle(data).then(data => {
			if (data && data.code === 0) {
				loadRoleUserSelectList()
				loadRoleUserMngList()
			} else {
				ElMessage.error(data.message)
			}
		}).catch(() => {
			ElMessage.error('设置失败')
		}).finally(() => {
			// state.listLoading = false
		})
	}
</script>